﻿@page "/posts/tagged/{Slug}"
@inject MarkdownBlog Blog
@inject AppConfig AppConfig

@if (selectedTag != null)
{
    <PageTitle>@selectedTag tagged posts</PageTitle>

    <div class="relative bg-gray-50 dark:bg-gray-900 px-6 pt-16 pb-20 lg:px-8 lg:pt-24 lg:pb-28">
        <div class="absolute inset-0">
            <div class="h-1/3 bg-white dark:bg-black sm:h-2/3"></div>
        </div>
        <div class="relative mx-auto max-w-7xl">
            <BlogTitle Heading=@($"All posts tagged in <b>{selectedTag}</b>") />
        </div>
        <div class="relative my-4 mx-auto max-w-7xl">
            <div class="flex flex-wrap justify-center">
                @foreach (var tag in allTags.OrderByDescending(tag => tagCounts[tag]))
                {
                    if (tag == selectedTag)
                    {
                        <span class="mr-2 mb-2 text-xs leading-5 font-semibold bg-indigo-600 text-white rounded-full py-1 px-3 flex items-center space-x-2">@tag</span>
                    }
                    else
                    {
                        <a href="@Blog.GetTagLink(tag)" class="mr-2 mb-2 text-xs leading-5 font-semibold bg-slate-400/10 rounded-full py-1 px-3 flex items-center space-x-2 hover:bg-slate-400/20 dark:highlight-white/5">@tag</a>
                    }
                }
            </div>
        </div>
        <div class="mt-12 relative mx-auto max-w-7xl">
            <BlogPosts Posts=@Blog.GetPosts(tag: selectedTag ?? "unknown") />

            <div class="mt-8 text-center">
                <a class="text-sm font-semibold hover:underline" href="@Blog.GetPostsLink()">view all posts</a>
            </div>
        </div>
    </div>
}
else
{
    <div class="mt-3 mb-20 mx-auto max-w-fit">
    @if (error != null)
    {
        <ErrorSummary Status=@error />
    }
    else
    {
        <Loading />
    }
    </div>
}

@code {
    [Parameter] public required string Slug { get; set; }

    string? selectedTag;
    List<MarkdownFileInfo> allPosts = new();
    List<string> allTags = new();
    Dictionary<string, int> tagCounts = new();
    ResponseStatus? error;

    void load()
    {
        selectedTag = Blog.GetTagBySlug(Slug);
        allPosts = Blog.GetPosts();
        allTags = allPosts.SelectMany(x => x.Tags).Distinct().ToList();
        tagCounts = new();
        allTags.Each(tag => tagCounts[tag] = allPosts.Count(x => x.Tags.Safe().Contains(tag)));
    }

    protected override void OnInitialized() => load();

    protected override void OnParametersSet() => load();
}
